import { useState, useEffect, useCallback } from "react";
import { Button, Input } from "antd";
import { request } from "../../../../common/request";
import { urls } from "../../../../common/urls";
import { encryptStr } from "../../../../util/index";
import "./index.less";

function GroupOperate(props: any) {
  const [groupList, setGroupList] = useState([] as any);
  const getList = () => {
    request({
      method: "post",
      data: {
        method: urls.groupOperateList,
      },
    }).then((res: any) => {
      setGroupList(res.data);
    });
  };
  const handleAddGroup = useCallback(() => {
    const list = groupList.concat({
      id: "",
      name: "",
    });
    setGroupList(list);
  }, [groupList]);

  const handleOperate = (name: string, id: string) => {
    let params = {};
    if(id) {
      params = {
        method: urls.updateGroupOperate,
        id,
        name
      }
    }
    else {
      params = {
        method: urls.addGroupOperate,
        name,
      }
    }
    request({
      method: "post",
      data: params,
    }).then(() => {
      getList();
    });
  };
  const handleDelItem = (x: any) => {
    if(x.id) {
      request({
        method: "post",
        data: {
          method: urls.delGroupOperate,
          id: encryptStr(JSON.stringify(x.id)),
        },
      }).then(() => {
        getList();
      }); 
    }
  }

  useEffect(() => {
    getList();
  }, []);

  return (
    <>
      <div className="user-content">
        {groupList.map((x: any, i: number) => {
          return (
            <div className="link-item" key={i}>
              <div>
                <Input
                  placeholder="请输入分组名称"
                  onPressEnter={(e: any) => handleOperate(e.target.value, x.id)}
                  defaultValue={x.name}
                  className="add-group-operate-item"
                />
              </div>
              <div onClick={() => handleDelItem(x)}>
                <img
                  className="add-group-operate-icon"
                  src="/assets/icon/txl_fz_scfz@2x.png" alt="" 
                />
              </div>
            </div>
          );
        })}
      </div>
      <Button
        type="primary"
        className="add-group-operate-btn"
        onClick={handleAddGroup}
      >
        添加分组
      </Button>
    </>
  );
}
export default GroupOperate;
